package com.hao.generator;

import com.hao.wms.domain.*;
import com.hao.wms.util.XmlUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.text.MessageFormat;

public class CodeGenerator {
    private static Configuration config;

    static {
        config = new Configuration(Configuration.VERSION_2_3_22);
        try {
            config.setDirectoryForTemplateLoading(new File("templates"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
//        generator();
        System.out.println("代码生成成功");
    }
    private static void generator() throws Exception {
        ClassInfo classInfo = new ClassInfo(Client.class);
        //dao
        createFile(classInfo,"IDao.java","src/main/java/{0}/dao/I{1}Dao.java");
        createFile(classInfo,"DaoImpl.java","src/main/java/{0}/dao/impl/{1}DaoImpl.java");
        //service
        createFile(classInfo,"IService.java","src/main/java/{0}/service/I{1}Service.java");
        createFile(classInfo,"ServiceImpl.java","src/main/java/{0}/service/impl/{1}ServiceImpl.java");
        //queryObject
        createFile(classInfo,"QueryObject.java","src/main/java/{0}/query/{1}QueryObject.java");
        //action
        createFile(classInfo,"Action.java","src/main/java/{0}/mvc/{1}Action.java");
        //jsp
        createFile(classInfo,"list.jsp","src/main/webapp/WEB-INF/views/{2}/list.jsp");
        createFile(classInfo,"input.jsp","src/main/webapp/WEB-INF/views/{2}/input.jsp");
        //hbm
        createFile(classInfo,"hbm.xml","src/main/resources/{0}/domain/{1}.hbm.xml");
        //追加xml
        appendXmlFile(classInfo,"dao.xml","src/main/resources/dao.xml");
        appendXmlFile(classInfo,"service.xml","src/main/resources/service.xml");
        appendXmlFile(classInfo,"action.xml","src/main/resources/action.xml");



    }
    private static void createFile(ClassInfo classInfo,String templateName,String path) throws Exception {
        Template template = config.getTemplate(templateName);
        String filePath = MessageFormat.format(path,classInfo.getBasePkg().replace(".","/"),classInfo.getClassName(),classInfo.getObjectName());
        File file = new File(filePath);
        if(!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
        }
        template.process(classInfo, new FileWriter(file));
    }
    private static void appendXmlFile(ClassInfo classInfo,String templateName,String targetFile) throws Exception {
        Template template = config.getTemplate(templateName);
        StringWriter out = new StringWriter();
        template.process(classInfo,out);
        String appendXml = out.toString();
        XmlUtil.appendXML(new File(targetFile),appendXml);
    }

}
